package com.jiubanqingchen.wish.framework.base.controller;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Aop;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.Render;
import com.jiubanqingchen.wish.framework.base.user.IUser;
import com.jiubanqingchen.wish.framework.enums.SystemStatus;
import com.jiubanqingchen.wish.framework.render.renderFactory.WishRenderFactory;

import java.util.List;
import java.util.Map;

/**
 * @author light_dust
 * @since 2020/12/10 20:26
 */
@SuppressWarnings("unchecked")
public class BaseController extends Controller implements IBaseController {

    private Render render;

    @Inject
    WishRenderFactory wishRenderFactory;

    @Override
    @NotAction
    public Record getRawDataToRecord() {
        Map<String, Object> mapData = getRawDataToObject(Map.class);
        return mapData == null ? null : new Record().setColumns(mapData);
    }

    @Override
    @NotAction
    public <T> T getRawDataToObject(Class<T> tClass) {
        if (StrKit.notBlank(getRawData())) {
            return JSON.parseObject(getRawData(), tClass);
        }
        return null;
    }

    @Override
    @NotAction
    public <T> List<T> getRawDataToObjectArray(Class<T> tClass) {
        if (StrKit.notBlank(getRawData())) {
            return JSON.parseArray(getRawData(), tClass);
        }
        return null;
    }

    @Override
    @NotAction
    public Record getExtDataToRecord() {
        return new Record().setColumns(getKv());
    }

    @Override
    public Kv getQueryParams() {
        return getKv();
    }

    @Override
    @NotAction
    public void renderJson(SystemStatus systemStatus) {
        render = wishRenderFactory.getJsonRender(systemStatus);
    }

    @Override
    @NotAction
    public void renderJson(SystemStatus systemStatus, Object data) {
        render = wishRenderFactory.getJsonRender(systemStatus, data);
    }

    @Override
    public void renderJson(SystemStatus systemStatus, Object data, String causeMessage) {
        render = wishRenderFactory.getJsonRender(systemStatus, data,causeMessage);
    }

    @Override
    public IUser getCurrentUser() {
        return Aop.get(IAdminService.class).getAdminUser(getRequest());
    }

    @Override
    public String getCurrentToken() {
        return Aop.get(IAdminService.class).getCurrentToken(getRequest());
    }

    @Override
    @NotAction
    public Render getRender() {
        return this.render == null ? super.getRender() : this.render;
    }
}
